package v4

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"mindonmap/models"
	"mindonmap/pkgs/e"
	"mindonmap/pkgs/setting"
	"mindonmap/pkgs/util"
	"mindonmap/validation"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type UserDevices struct {
	ID             int       `json:"id"`
	UserId         int       `json:"user_id"`
	UserAccount    string    `json:"user_account"`
	DeviceID       string    `json:"device_id"`
	System         string    `json:"system"`
	DeviceName     string    `json:"device_name"`
	Version        string    `json:"version"`
	FirstLoginTime time.Time `json:"first_login_time"`
	LastLoginTime  time.Time `json:"last_login_time"`
}

func DeviceFirstLogin(c *gin.Context) {
	var json UserDevices
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	Userid, err := GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}
	json.UserId = Userid
	data := make(map[string]interface{})
	data["device_id"] = json.DeviceID
	data["user_id"] = json.UserId
	data["user_account"] = json.UserAccount
	data["system"] = json.System
	data["device_name"] = json.DeviceName
	res := models.AddUserDevice(data)

	code := e.SUCCESS
	if res {
		code = e.SUCCESS
	} else {
		data = nil
		code = e.ERROR_ADD
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

// 保存设备
func DeviceNotFirstLogin(c *gin.Context) {
	Userid, err := GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}

	var json models.UserDevice
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	valid := validation.Validation{}
	valid.Required(json.DeviceID, "device_id").Message("不能为空")

	json.UserId = Userid

	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		res := models.EditUserDevice(json.UserId, json.DeviceID, json)
		code = e.SUCCESS
		if res {
			code = e.SUCCESS
		} else {
			code = e.ERROR_ADD
		}

	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": json,
	})
}

// 获取用户设备
func GetDeviceList(c *gin.Context) {

	var jsons models.MainPlatform
	if err := c.BindJSON(&jsons); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	valid := validation.Validation{}
	valid.Required(jsons.Tid, "t_id").Message("不能为空")
	// curl 验证token
	v := "t_id=" + strconv.Itoa(jsons.Tid) + "&e_id=" + jsons.Eid + "&token=" + jsons.Token
	baseurl := setting.GetLoginurl() + "/account/profile"
	client := &http.Client{Timeout: 60 * time.Second}
	responseToken, err := client.Post(baseurl, "application/x-www-form-urlencoded", strings.NewReader(v))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	defer responseToken.Body.Close()
	body, err := ioutil.ReadAll(responseToken.Body)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	var datas models.Webinfo
	err = json.Unmarshal(body, &datas)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	data := make(map[string]interface{})
	data["error"] = datas.Error
	code := e.INVALID_PARAMS
	if !valid.HasErrors() {
		code = e.SUCCESS
		data["lists"] = models.GetDeviceLists(util.GetPage(c), setting.PageSize, jsons.Tid)
		//data["total"] = models.GetMindFlowTotal(mapsdata)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}
